#include "World.h"
#include "RGBColor.h"
#include "SingleSphere.h"
#include <math.h>

void World::build(void)
{
	vp.hres = 200;
	vp.vres = 200;
	vp.gamma = 1.0;
	
	backgroundColor = RGBColor(0, 0, 0);
	//continue code hereeee
	tracer_ptr = new SingleShere(this);

	sphere.centerPoint = 0.0;
	sphere.radius = 85.0;

}

void World::render_scene(void) const
{
	RGBColor pixelColor;
	Ray ray;
	double zw = 100.0;
	double x, y;

	//open_window(vp.hres, vp.vres);
	ray.d = Vector3D(0, 0, -1);

	for (int r = 0; r < vp.vres; r++)
	{
		for (int c = 0; c <= vp.hres; c++)
		{
			x = vp.s * (c - 0.5 * (vp.hres - 1.0));
			y = vp.s * (r - 0.5 * (vp.vres - 1.0));

			ray.o = Point3D(x, y, zw);
			pixelColor = tracer_ptr->TraceRay(ray);
			display_pixels(r, c, pixelColor);
		}
	}
}
// ------------------------------------------------------------------ clamp

RGBColor
World::MaxToOne(const RGBColor& c) const  {
	float max_value = max(c.r, max(c.g, c.b));

	if (max_value > 1.0)
		return (c / max_value);
	else
		return (c);
}


// ------------------------------------------------------------------ clamp_to_color
// Set color to red if any component is greater than one

RGBColor
World::ClampToColor(const RGBColor& raw_color) const {
	RGBColor c(raw_color);

	if (raw_color.r > 1.0 || raw_color.g > 1.0 || raw_color.b > 1.0) {
		c.r = 1.0; c.g = 0.0; c.b = 0.0;
	}

	return (c);
}


// ---------------------------------------------------------------------------display_pixel
// raw_color is the pixel color computed by the ray tracer
// its RGB floating point components can be arbitrarily large
// mapped_color has all components in the range [0, 1], but still floating point
// display color has integer components for computer display
// the Mac's components are in the range [0, 65535]
// a PC's components will probably be in the range [0, 255]
// the system-dependent code is in the function convert_to_display_color
// the function SetCPixel is a Mac OS function


void
World::display_pixels(const int row, const int column, const RGBColor& raw_color) const {
	RGBColor mapped_color;

	//what is it?

	if (vp.show_out_of_gamut)
		mapped_color = ClampToColor(raw_color);
	else
		mapped_color = max_to_one(raw_color);

	if (vp.gamma != 1.0)
		mapped_color = mapped_color.powc(vp.inv_gamma);

	//have to start from max y coordinate to convert to screen coordinates
	int x = column;
	int y = vp.vres - row - 1;

	paintArea->setPixel(x, y, (int)(mapped_color.r * 255),
		(int)(mapped_color.g * 255),
		(int)(mapped_color.b * 255));
}